package leetcode;

public class RomanAndInteger {

	public static void main(String[] args) {
		RomanAndInteger object = new RomanAndInteger();
		System.out.println(object.romanToInt("MCMXCVI"));
	}
	
	public int romanToInt(String s) {
        //罗马数字由7个基本符号组成, 分别为I，V，X(10), L(50), C(100), D(500), M(1000)
        //只有三个小数(I, C, X)可以放在大数的左边表示减，且只能放一个(放在右边时只能放三个)
        //D 和 M 左 边的小数字只能用 C 
        //L 和 C 左边的小数字只能用X
        //V 和 X 左边的小数字只能用I
        char c[] = s.toCharArray();
        int res = 0;
        for(int i = 0; i < c.length; i++){
            switch(c[i]){
            case 'I':
            	res += 1;
            break;
            case 'V':
            	res += 5;
            	break;
            case 'X':
            	res += 10;
            	break;
            case 'L':
            	res += 50;
            	break;
            case 'C':
            	res += 100;
            	break;
            case 'D':
            	res += 500;
            	break;
            case 'M':
            	res += 1000;
            	break;
            }
        }
        System.out.println(res);
        if(s.indexOf("IV")!=-1){res-=2;}
        if(s.indexOf("IX")!=-1){res-=2;}
        if(s.indexOf("XL")!=-1){res-=20;}
        if(s.indexOf("XC")!=-1){res-=20;}
        if(s.indexOf("CD")!=-1){res-=200;}
        if(s.indexOf("CM")!=-1){res-=200;}
        return res;
    }
	
	//amazing solution
	//整数转为罗马数字
    public String intToRoman(int num) {
        String M[] = {"", "M", "MM", "MMM"};
        String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10];
    }
}
